package com.mf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mf.constant.ConstantBasic;
import com.mf.utils.UtilIdGenerator;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.mf.entity.dto.DtoSmash;
import com.mf.entity.req.search.SearchReqSmash;
import com.mf.mapper.MapperSmash;
import com.mf.service.ServiceSmash;

import java.time.LocalDate;
import java.time.LocalTime;


@Service
public class ImplServiceSmash extends ServiceImpl<MapperSmash, DtoSmash> implements ServiceSmash {

    /**
     * 参数查询条件
     */
    @Override
    public LambdaQueryWrapper<DtoSmash> fillParams(SearchReqSmash params) {
        LambdaQueryWrapper<DtoSmash> wrapper = loadQw();
        if (StringUtils.isNotEmpty(params.getKey())) {
            wrapper.and(w -> {
                w.like(DtoSmash::getCustomerName, params.getKey())
                        .or()
                        .like(DtoSmash::getWorkFlag, params.getKey())
                        .or()
                        .like(DtoSmash::getWorkCode, params.getKey())
                        .or()
                        .like(DtoSmash::getActualWorkFlag, params.getKey())
                        .or()
                        .like(DtoSmash::getActualWorkCode, params.getKey());
            });
        }
        wrapper.eq(ObjectUtils.isNotEmpty(params.getCustomerId()), DtoSmash::getCustomerId, params.getCustomerId())
                .eq(ObjectUtils.isNotEmpty(params.getStatus()), DtoSmash::getStatus, params.getStatus());
        return wrapper;
    }

    /**
     * 保存
     */
    @Override
    public void saveSmash(DtoSmash dtoSmash) {
        LambdaQueryWrapper<DtoSmash> w = loadQw();
        LocalDate date = LocalDate.now();

        w.between(DtoSmash::getCreatedTime, date.atStartOfDay(), date.atTime(LocalTime.MAX))
                .orderByDesc(DtoSmash::getCreatedTime)
                .last("limit 1");

        DtoSmash smash = getOne(w);
        if (ObjectUtils.isNotEmpty(smash)) {
            dtoSmash.setWorkCode(UtilIdGenerator.generateId(ConstantBasic.SMASH_CODE_PREFIX,
                    ConstantBasic.CODE_NUMBER_LENGTH, smash.getWorkCode()));
        } else {
            dtoSmash.setWorkCode(UtilIdGenerator.generateId(ConstantBasic.SMASH_CODE_PREFIX,
                    ConstantBasic.CODE_NUMBER_LENGTH, ConstantBasic.START_NUMBER));
        }
        this.save(dtoSmash);
    }
}